// Invasion.Wrapper.h
#include <algorithm>
#include "../../Library/Invasion/AppInterface.h"

#pragma once

using namespace System;

namespace InvasionWrapper {

	public ref class Line
	{
	public:
		OpenCvSharp::CvPoint P1;
		OpenCvSharp::CvPoint P2;
	};


	public ref class Config
	{
	public:
		int MinObjArea;
		bool  bDrawTrack;
		bool  bDrawObjs;
		bool  bDrawDirection;
		bool  bDrawROI;

		array<OpenCvSharp::CvPoint>^ Roi;

		bool flagObjCount;
		Line CountCrossLine;
		Line CountDirLine;


		bool flagCrossLine;
		Line CrossLine;

		Config()
		{
			Roi = gcnew array<OpenCvSharp::CvPoint>(0);
		}

	};

	public ref class ObjInfo
	{
	public:
		bool Stop;
		bool CrossLine;
		bool IllegalDir;
		bool ChangeChannel;
		bool Count;
		array<OpenCvSharp::CvRect>^  PositionHistory;
	};


	public ref class InvasionDetector
	{
		// TODO: Add your methods for this class here.
	public:
		InvasionDetector()
		{
			m_pDetector = new CAppInterface();
		}

		void SetConfig(Config^ config)
		{
			AppParam parm;
			parm.bDrawDirection = config->bDrawDirection;
			parm.bDrawObjs = config->bDrawObjs;
			parm.bDrawROI = config->bDrawROI;
			parm.bDrawTrack = config->bDrawTrack;
			
			for (int i=0; i<config->Roi->Length; ++i)
			{
				parm.Roi.push_back(cvPoint(config->Roi[i].X, config->Roi[i].Y));
			}

			m_pDetector->SetParams(parm);
		}

		array<ObjInfo^>^ Process(OpenCvSharp::IplImage^ image)
		{
			ResultInfo_V* r  = m_pDetector->FramePro((IplImage*) image->CvPtr.ToPointer());
			array<ObjInfo^>^ result = gcnew array<ObjInfo^>(r->size());
			int idx = 0;
			for (ResultInfo_V::const_iterator  i = r->begin(); i != r->end(); i++)
			{
				ObjInfo^ item = gcnew ObjInfo();
				item->ChangeChannel = (*i)->bChangeChannel;
				item->Count = (*i)->bCount;
				item->CrossLine = (*i)->bCrossLine;
				item->IllegalDir = (*i)->bIllegalDir;
				item->Stop = (*i)->bStop;
				
				array<OpenCvSharp::CvRect>^ positions = gcnew array<OpenCvSharp::CvRect>((*i)->pObjPosList->size());
				for (ObjPosList_V::const_iterator j = (*i)->pObjPosList->begin(); j != (*i)->pObjPosList->end(); ++j)
				{
					OpenCvSharp::CvRect^ rect = gcnew OpenCvSharp::CvRect();
					rect->X = (*j).x;
					rect->Y = (*j).y;
					rect->Width = (*j).width;
					rect->Height = (*j).height;

					item->PositionHistory = positions;
				}

				result[idx++] = item;
			}

			return result;
		}
	private:
		CAppInterface* m_pDetector;

	};
}
